<?php


namespace App\Extensions\Actions\Upload;

use App\PlantVariety;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Encore\Admin\Actions\Response;
use App\Extensions\Actions\RowAction;
use Illuminate\Support\Facades\Storage;

class PlantCertUploadAction extends RowAction
{
    public $name = '已审定';

    public function handle(PlantVariety $model, Request $request): Response
    {
        $user = Admin::user();
        if ($user['role_type'] == 1) {
            $model->status = 1;
        }
        $cert_date = $request->get('cert_date') ?: $model['cert_date'];
        $approved_no = $request->get('approved_no') ?: $model['approved_no'];
        $cert_no = $request->get('cert_no') ?: $model['cert_no'];
        $publication_no = $request->get('publication_no') ?: $model['publication_no'];
        $res = PlantVariety::query()->where('approved_no', $approved_no)->orWhere('cert_no', $cert_no)->get()
            ->filter(function ($item) use ($model) {
                return $item['id'] != $model['id'];
            })->count();
        if ($res) {
            $this->response()->status = false;
            return $this->response()->swal()->error('审定编号或证书编号重复');
        }
        if ($file = $request->file('cert')) {
            $model->storeFile($file, 'cert');
        } elseif (!$model->cert) {
            $this->response()->status = false;
            return $this->response()->swal()->error('请上传证书');
        }
        $model->cert_date = $cert_date;
        $model->approved_no = $approved_no;
        $model->cert_no = $cert_no;
        $model->publication_no = $publication_no;
        $model->save();
        return $this->response()->success('操作成功')->refresh();
    }

    public function form()
    {
        $model = $this->row;
        $this->text('name', __('名称'))->default($model['name'])->disable();
        $this->date('cert_date', __('下证时间'))->default($model['cert_date'])->required();
        $this->text('approved_no', __('审定编号'))->default($model['approved_no'])->required();
        $this->text('cert_no', __('证书编号'))->default($model['cert_no'])->required();
        $this->text('publication_no', __('公告号'))->default($model['publication_no'])->required();
        $this->file('cert', '上传证书')->hidePreview();
    }

}
